<template>
  <view class="payment-page">
    <view class="payment-info">
      <!-- [修改] 绑定动态标签 -->
      <text class="label">{{ paymentLabel }}</text>
      <!-- [修改] 绑定动态金额 -->
      <text class="amount">¥{{ paymentAmount.toFixed(2) }}</text>
      <view id="timer-container" class="countdown-timer">
        支付剩余时间 <text id="timer">{{ countdownText }}</text>
      </view>
    </view>

    <view class="payment-options">
      <view class="options-title">选择支付方式</view>
      <view class="option-item" @click="selectPayment('alipay')" :class="{active: selectedPayment === 'alipay'}">
        <image src="/static/icons/alipay.svg" class="icon" mode="aspectFit"></image>
        <view class="details">
          <text class="name">支付宝</text>
          <text class="desc">推荐支付宝用户使用</text>
        </view>
        <view class="radio-check">
          <uni-icons v-if="selectedPayment === 'alipay'" type="checkmarkempty" size="18" color="#fff"></uni-icons>
        </view>
      </view>
      <view class="option-item" @click="selectPayment('wechatpay')" :class="{active: selectedPayment === 'wechatpay'}">
        <image src="/static/icons/wechatpay.svg" class="icon" mode="aspectFit"></image>
        <view class="details">
          <text class="name">微信支付</text>
        </view>
        <view class="radio-check">
           <uni-icons v-if="selectedPayment === 'wechatpay'" type="checkmarkempty" size="18" color="#fff"></uni-icons>
        </view>
      </view>
    </view>

    <view class="sticky-footer" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <!-- [修改] 绑定动态金额 -->
      <button class="confirm-btn" :disabled="isTimeout" @click="confirmPayment">
        确认支付 ¥{{ paymentAmount.toFixed(2) }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useSystemInfo } from '@/composables/useSystemInfo';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

const { safeAreaInsets } = useSystemInfo();

// ---- 响应式状态 ----
const orderInfo = reactive({
    orderId: null,
    serviceMainName: '加载中...',
    orderStartMoney: 0.00,
    orderEndMoney: 0.00,
		orderStatus: null,
});
// payType 决定了整个页面的行为：'deposit' (付订金) 或 'final' (付尾款)
const payType = ref(''); 
const selectedPayment = ref('alipay');
const totalSeconds = ref(15 * 60);
const isTimeout = ref(false);
let timer = null;

// ---- 计算属性 ----

// 根据支付类型，自动计算出当前需要支付的金额
const paymentAmount = computed(() => {
    if (payType.value === 'deposit') {
        return orderInfo.orderStartMoney;
    }
    if (payType.value === 'final') {
        return orderInfo.orderEndMoney;
    }
    return 0.00;
});

// 根据支付类型，自动生成页面顶部标签
const paymentLabel = computed(() => {
    if (payType.value === 'deposit') return '需支付订金';
    if (payType.value === 'final') return '需支付尾款';
    return '需支付金额';
});

// 格式化的倒计时文本
const countdownText = computed(() => {
  if (isTimeout.value) return '订单已超时';
  const minutes = String(Math.floor(totalSeconds.value / 60)).padStart(2, '0');
  const seconds = String(totalSeconds.value % 60).padStart(2, '0');
  return `${minutes}:${seconds}`;
});

// ---- API & 事件处理 ----

// 根据订单ID获取订单详情
const fetchOrderDetail = async (id) => {
    try {
        const data = await request({
            url: `/orders/${id}`, // 使用您已完成的GET接口
            method: 'GET'
        });
        Object.assign(orderInfo, data);
    } catch (error) {
        console.error("获取订单详情失败:", error);
        uni.showToast({ title: '加载订单信息失败', icon: 'error' });
    }
};

// 选择支付方式
const selectPayment = (method) => { selectedPayment.value = method; };

// 启动倒计时
const startCountdown = () => {
  timer = setInterval(() => {
    if (totalSeconds.value > 0) {
      totalSeconds.value--;
    } else {
      isTimeout.value = true;
      clearInterval(timer);
    }
  }, 1000);
};

// 确认支付
const confirmPayment = () => {
  if (isTimeout.value) return;
  if (selectedPayment.value !== 'alipay') {
    return uni.showToast({ title: '暂不支持其他支付方式', icon: 'none' });
  }

  uni.showLoading({ title: '正在创建支付...' });
  
  // [核心] 根据 payType 构造不同的请求体
  const baseParams = {
      orderId: orderInfo.orderId,
      serviceMainName: orderInfo.serviceMainName,
			orderStatus: orderInfo.orderStatus,
  };

  if (payType.value === 'deposit') {
      baseParams.orderStartMoney = orderInfo.orderStartMoney;
  } else if (payType.value === 'final') {
      baseParams.orderEndMoney = orderInfo.orderEndMoney;
  }

  console.log('发送给支付接口的参数:', baseParams);

  uni.request({
    url: BASE_URL + '/api/alipay/pay',
    method: 'POST',
    data: baseParams, // 发送构造好的参数
    header: {
      'X-User-ID': uni.getStorageSync('userId'),
      'Content-Type': 'application/json',
    },
    success: (res) => {
      if (res.statusCode === 200 && typeof res.data === 'string' && res.data.startsWith('<form')) {
        const htmlContent = res.data;
        // #ifdef MP-WEIXIN
        const tempFilePath = `${wx.env.USER_DATA_PATH}/alipay_temp.html`;
        uni.getFileSystemManager().writeFile({
          filePath: tempFilePath, data: htmlContent, encoding: 'utf8',
          success: () => uni.navigateTo({ url: `/pages/order-payment/alipay-webview?url=${encodeURIComponent(tempFilePath)}` }),
          fail: () => uni.showToast({ title: '支付页面加载失败', icon: 'none' })
        });
        // #endif
        // #ifndef MP-WEIXIN
        const blob = new Blob([htmlContent], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        uni.navigateTo({ url: `/pages/order-payment/alipay-webview?url=${encodeURIComponent(url)}` });
        // #endif
      } else {
        console.error('获取支付页面失败:', res);
        uni.showToast({ title: '创建支付失败，请重试', icon: 'none' });
      }
    },
    fail: (err) => {
      console.error('支付请求失败:', err);
      uni.showToast({ title: '网络请求失败', icon: 'none' });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

// ---- 生命周期钩子 ----
onLoad(async (options) => {
  const currentOrderId = options.orderId;
  payType.value = options.payType || 'deposit'; // 从URL获取支付类型

  if (currentOrderId) {
    await fetchOrderDetail(currentOrderId); // 等待获取订单详情
    startCountdown(); // 然后再启动倒计时
  } else {
    uni.showToast({ title: '订单参数错误', icon: 'error' });
    setTimeout(() => uni.navigateBack(), 1500);
  }
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style lang="scss" scoped>
.payment-page {
  background-color: $uni-bg-color;
  min-height: 100vh;
}

.payment-info {
  text-align: center;
  padding: 60rpx 40rpx;
  background-color: $uni-bg-color-white;

  .label {
    font-size: 28rpx;
    color: $uni-text-color-light;
    margin-bottom: 16rpx;
    display: block;
  }
  .amount {
    font-size: 72rpx;
    font-weight: bold;
    color: $uni-text-color;
    margin-bottom: 30rpx;
    display: block;
  }
  .countdown-timer {
    font-size: 28rpx;
    color: $uni-color-warning;
  }
}

.payment-options {
  margin: 30rpx;
  background-color: $uni-bg-color-white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);

  .options-title {
    padding: 30rpx 40rpx;
    font-size: 32rpx;
    font-weight: 500;
    border-bottom: 1px solid $uni-bg-color;
  }
  
  .option-item {
    display: flex;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1px solid $uni-bg-color;
    transition: background-color 0.2s;
    
    &:last-child {
      border-bottom: none;
    }

    .icon {
      width: 48rpx;
      height: 48rpx;
      margin-right: 30rpx;
    }

    .details {
      flex-grow: 1;
      .name {
        font-size: 32rpx;
        font-weight: 500;
        display: block;
      }
      .desc {
        font-size: 24rpx;
        color: $uni-text-color-light;
        display: block;
      }
    }

    .radio-check {
      width: 44rpx;
      height: 44rpx;
      border-radius: 50%;
      border: 2px solid $uni-border-color;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: all 0.2s;
    }
    
    &.active {
      .radio-check {
        border-color: $uni-primary;
        background-color: $uni-primary;
      }
    }
  }
}

.sticky-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $uni-bg-color-white;
  padding: 24rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);

  .confirm-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(135deg, $uni-primary, $uni-accent);
    color: white;
    border-radius: 45rpx;
    font-size: 32rpx;
    font-weight: 500;

    &[disabled] {
      background: #E0E0E0;
      background-image: none;
    }
  }
}
</style>